/**
 * 单个东东, 元素绝对定位
 */
var Item = function(data) {
	this.data = data; //原始数据id, link, icon, type, parentId
	//还包括x,y
	this.dom = null; //dom引用
	this.nextItem = null;
};
/**
 * 文件夹
 */
var Folder = function(data, childDatas) {
	Item.call(this, data); //属性共享一下
	/** 作为基础属性
	 *  this.type = -1;
	 *  this.parentId = -1;
	 */
	this.getChildHTML(childDatas);
};
/*
 * 单个东东和文件夹的共同行为, 实例的存储用单向链表的结构
 */
var ItemBase = {
	template : ['<a class="cont link" href="javascript:;" data-link="{link}">',
					'<span class="item_{icon}" {style}></span>',
				'</a>',
				'<a class="name link" href="javascript:;" data-link="{link}">{title}</a>'],
				//模板
	iconMap : {
				0 : 'blog',
				1 : 'photo',
				2 : 'tweet',
				3 : 'music'
		},
	genDom : function(x, y){
		var div = document.createElement('div'),
			iconMap = {
				0 : 'blog',
				1 : 'photo',
				2 : 'tweet',
				3 : 'music'
			}, icon, style = '';
		this.data.icon = iconMap[this.data.type];
		div.className = 'item';		
		div.style.cssText = 'top:' + y + 'px;left:' + x + 'px;';
		div.setAttribute('data-id', this.data.id);
		if(this.data.img){
			style='style="background-image:url('+this.data.img+')"';
		}
		div.innerHTML = QZFL.string.format(this.template.join(''), QZFL.object.extend({'style' : style}, this.data));
		this.dom = div;
		//坐标计算
		this.x = x;
		this.y = y;
		return div;
	},
	setNextItem : function(item){
		this.nextItem = item;
	},
	setPreItem : function(item){
		
	},
	//移动到指定的坐标
	moveTo : function(x , y){
		QZFL.effect.run(this.dom, {
			'top' : y,
			'left' : x
		},{
	        duration : 200,
	        easing : 'ease-in'
	    });
	    this.x = x;
	    this.y = y;
	},
	setPosition : function(x, y){
		this.dom.style.cssText = ('left:' + x + 'px;top:'+y+'px;');
	},
	toFolderView : function(){
		var span;
		if(this.data.type != -1){//非文件夹
			span = this.dom.firstChild.firstChild;
			span.className = 'item_folder';
			span.innerHTML = '<span class="item_s"><i class="icon_'+this.iconMap[this.data.type]+'"></i></span>';
		}
		QZFL.css.addClassName(this.dom, 'item_hover');
	},
	toNormal : function(){
		var span;
		if(this.data.type != -1){//非文件夹
			span = this.dom.firstChild.firstChild;
			span.className = 'item_' + this.iconMap[this.data.type];
			span.innerHTML = '';
		}
		QZFL.css.removeClassName(this.dom, 'item_hover');
	},
	toFloder : function(x, y){
		
	},
	addItem : function(item){
		var data, id, me;
		if(this.data.type == -1){
			ItemFactory.origData[this.data.id].push(item.data);
			item.data.parentId = this.data.id;
			QZONE.Finder.db.add(item.data.parentId);
		}else{
			data = {
				type  : -1,
				title : '文件夹'
			};
			id = QZONE.Finder.db.add(data);
			data.id = id;
			ItemFactory.origData[data.id] = [];
			item.data.parentId = data.id;
			this.data.parentId = data.id;
			ItemFactory.origData[data.id].push(item.data);
			ItemFactory.origData[data.id].push(this.data);
			QZONE.Finder.db.delete(this.data.id);
			QZONE.Finder.db.delete(item.data.id);
			QZONE.Finder.db.add(this.data);
			QZONE.Finder.db.add(item.data);
			this.data = data;
			this.dom.setAttribute('data-id', data.id);
			ItemFactory._rawData[data.id] = data;
		}
		QZFL.dom.removeElement(item.dom);
	}
};

var FolderBase = {
	template : ['<a href="javascript:;" class="cont link" data-fid="{id}">',
					'<span class="item_folder">',
						'{childList}',
					'</span>',
				'</a>',
				'<a href="javascript:;" class="name link" data-fid="{id}">{title}</a>'],
	getChildHTML: function(data){
		var iconMap = {
			0 : 'blog',
			1 : 'photo',
			2 : 'tweet',
			3 : 'music'
		}, html = [];
		for(var i = 0, len = Math.min(data.length, 4); i < len; i++){
			html.push('<span class="item_s"><i class="icon_',iconMap[data[i].type],'" ',(this.data.img ? 'style="background-image:url('+this.data.img+')"' : ''),'></i></span>');
		}
		this.data.childList = html.join('');
	}	
};

QZFL.object.extend(Item.prototype, ItemBase);
QZFL.object.extend(Folder.prototype, ItemBase, FolderBase);
/**
 * 当前view的工厂
 */
var ItemFactory = {
	_rawData : {},
	origData : {},
	curItems : [],    //当前页面的对象
	init : function(rawData){
		ItemFactory.init = QZFL.emptyFn;//调用保护，只执行一次
		if(!(rawData && rawData.length)){
			return;
		}
		var itemList;
		for(var i = 0, len = rawData.length; i < len; i++){
			rawData[i].parentId = (rawData[i].parentId == undefined ? -1 : rawData[i].parentId);
			if(!(itemList = this.origData[rawData[i].parentId])){
				itemList = this.origData[rawData[i].parentId] = [];
			}
			itemList.push(rawData[i]);
			this._rawData[rawData[i].id] = rawData[i];
		}
		for(var i in this.origData){  //排序
			this.origData[i].sort(function(a, b){
				return a.index - b.index;
			});
		}
		this.Pager.init(this.origData[-1] || []);
	},
	setCurDataArray : function(curItems){
		this.curItems = curItems;
	},
	countXY : function(i){
		var x = (i % 7) * 135, y = Math.floor(i/7) * 117;
		return [x, y];
	},
	Pager : {
		data : null,
		pageSize : 21,
		curPage : 1,
		totalPage : 1,
		containerCache : {},
		conCache : {},
		inited : 0,
		init : function(data){
			if(this.inited){
				return false;
			}
			this.inited = 1;
			this.data = data;
			this.countPage();
			this.toPage(this.curPage);
			QZFL.event.delegate($('nav'), 'a', 'click', this.btnEvent);
			QZFL.event.addEvent($('_finder_prev'), 'click', this.prePage);
			QZFL.event.addEvent($('_finder_next'), 'click', this.nextPage);
			return true;
		},
		countPage : function(){
			this.totalPage = Math.ceil(this.data.length/this.pageSize);
		},
		renderPage : function(dom, dataArray, pageNo){
			var df = document.createDocumentFragment(), pos, ins, curItems = [];

			for(var i = 0, len = dataArray.length , meta; i < len; i++){
				pos = ItemFactory.countXY(i);
				if(dataArray[i].type == -1){
					ins = new Folder(dataArray[i], ItemFactory.origData[dataArray[i].id]);
					df.appendChild(ins.genDom(pos[0], pos[1]));
				}else{
					ins = new Item(dataArray[i]);
					df.appendChild(ins.genDom(pos[0], pos[1]));
				}
				curItems.push(ins);
			}
			dom.innerHTML = '';
			dom.appendChild(df);
			return curItems;
		},
		toPage: function(pageNo){
			var max, min, pageNo = parseInt(pageNo);
			if(pageNo <= this.totalPage && pageNo >= 1){
				max = Math.max(pageNo, this.curPage);
				min = Math.min(pageNo, this.curPage);
				this.curPage = pageNo;
				for(var i = min; i<= max; i++){
					this.createNextPages(i);
				}
				QZFL.effect.run($('finder_list_container'),{
					'marginLeft' : (this.curPage - 1) * (-945)
				},{
					'duration' : 500,
					easing : 'ease-out'
				});
				this.updateBtn(pageNo);
				ItemFactory.curItems = this.containerCache[pageNo];
			}
		},
		createNextPages : function(pageNo){
			var con, curItems;
			if(!(curItems = this.containerCache[pageNo])){
				con = document.createElement('div');
				con.className = 'qzmod_itemlist';
				$('finder_list_container').appendChild(con);
				this.conCache[pageNo] = con;
				curItems = this.renderPage(con, this.data.slice((pageNo - 1)* this.pageSize, pageNo * this.pageSize), pageNo);
				this.containerCache[pageNo] = curItems;
			}
		},
		nextPage : function(evt){
			var P = ItemFactory.Pager;
			P.toPage(P.curPage + 1);
			QZFL.event.preventDefault(evt);
		},
		prePage : function(evt){
			var P = ItemFactory.Pager;
			P.toPage(P.curPage - 1);
			QZFL.event.preventDefault(evt);
		},
		//更新导航区域
		updateBtn : function(pageNo){
			var html = [];
			for(var i = 1; i <= this.totalPage; i++){
				html.push('<a',i == pageNo ? ' class="current"' : '',' data-no="',i,'" href="javascript:;">',i,'</a>');
			}
			$('nav').innerHTML = html.join('');

			QZFL.css[pageNo == 1 ? 'addClassName' : 'removeClassName']($('_finder_prev'), 'hide');
			QZFL.css[pageNo == this.totalPage ? 'addClassName' : 'removeClassName']($('_finder_next'), 'hide');
		},
		btnEvent : function(evt){
			var index = this.dataset ? this.dataset.no : this.getAttribute('data-no');
			ItemFactory.Pager.toPage(index);
			QZFL.event.preventDefault(evt);
		}
	},
	//item添加到某个文件夹
	addToFolder : function(item, folder){
		//主要影响parentId
		
	},
	giveItemToNextPage : function(item){
		var p = this.Pager, items, dom, i = 1;
		while(item && (items = p.containerCache[p.curPage + i])){
			dom = items[0] && items[0].dom;
			if(dom){
				dom.parentNode.insertBefore(item.dom, dom);
				item = items[20];
				i++;
			}
		}
	},
	//item从给某个文件夹中移除
	removeFromFolder : function(item, folder){
		
	},
	getDataById : function(id){
		return this._rawData[id];
	},
	addItem : function(data){
		var ins = new Item(data), items = ItemFactory.curItems, s, to, id;
		id = QZONE.Finder.db.add(data);
		data.id = id;
		this._rawData[id] = data;
		this.origData[data.parentId] = this.origData[data.parentId] || [];
		this.origData[data.parentId].unshift(data);
		for(var i = 0, len = items.length; i < len; i++){
			if(items[i + 1]){
				items[i].moveTo(items[i + 1].x, items[i + 1].y);
			}else{
				if(len < 21){
					to = ItemFactory.countXY(i + 1);
					items[i].moveTo(to[0], to[1]);
				}else{
					s = items.splice(i, 1)[0];
					QZFL.dom.removeElement(s.dom);
				}
			}
		}
		if(!this.Pager.init(this.origData[-1] || [])){
			this.Pager.toPage(1);
			this.Pager.conCache[1].appendChild(ins.genDom(0, 0));
		}
		items.unshift(ins);
		if(items.length > 21){
			ItemFactory.giveItemToNextPage(items.pop());
		}
	},
	getItemById : function(id){
		var items = this.curItems, item, _i;
		for(var i = 0, len = items.length; i < len; i++){
			if(items[i].data.id == id){
				item = items[i];
				_i = i;
				break;
			}
		}
		return [_i,item];
	},
	Move : {
		inited : 0,
		itemIndex : 1,
		curItem : null,
		holder : {
			'index' : 1,
			'x' : 0,
			'y' : 0
		},
		init : function(id, x, y){
			var s = ItemFactory.getItemById(id);
			this.curItem = s[1];
			this.holder.index = this.itemIndex = s[0];
			this.holder.x = this.curItem.x;
			this.holder.y = this.curItem.y;
			this.curItem.setPosition(x, y);
			this.inited = 1;
			QZFL.css.addClassName(this.curItem.dom, 'item_move');
			QZFL.css.removeClassName(this.curItem.dom, 'item_over');
		},
		setPosition : function(x, y){
			this.curItem.setPosition(x, y);
		},
		backTo : function(){
			this.upOnTimer && window.clearTimeout(this.upOnTimer);
			if(this.curUpItem && this.curUpItem.data.id != this.curItem.data.id){ //当到了某个元素上面
				this.curUpItem.addItem(this.curItem);
				//元素移动
				var start = this.holder.index, items = ItemFactory.curItems;
				for(var j = this.holder.index + 1, _x, _y; j < items.length; j++){
					_x = items[j].x; _y = items[j].y;
					items[j].moveTo(this.holder.x, this.holder.y);
					this.holder.x = _x;this.holder.y = _y;
					this.replaceItem(items, j, this.holder.index);
					this.holder.index = j;
				}
				//删除数据
				ItemFactory.origData[-1] && ItemFactory.origData[-1].splice((ItemFactory.Pager.curPage - 1)*21 + start, 1);
				//展开分组
				ItemFactory.openFolder(this.curUpItem.data.id);
				//获得下一页的元素
				ItemFactory.getItemFromNextPage();
			}else{
				this.curItem.moveTo(this.holder.x, this.holder.y);
				QZFL.css.removeClassName(this.curItem.dom, 'item_move');
				this.curItem.toNormal();
			}
			this.inited = 0;
			this.curUpItem = null;
		},
		curUpItem : null,
		upOnTimer : null,
		upOn : function(x, y){
			var items = ItemFactory.curItems, item, _i, _x, _y, line = Math.ceil(y/117),
				len = items.length, start = Math.min((line - 1)*7, len - 1), end = Math.min(line*7, len), index,
				hit;
			for(var i = start; i < end; i++){
				if(items[i].data.id == this.curItem.data.id){
					continue;
				}
				/*
				if(items[i].x > x && x > items[i].x - 60 && items[i].y < y && items[i].y + 76 > y){
						if(i < this.holder.index){
							for(var j = this.holder.index - 1; j >= i; j--){
								_x = items[j].x; _y = items[j].y;
								items[j].moveTo(this.holder.x, this.holder.y);
								this.holder.x = _x;this.holder.y = _y;
								this.replaceItem(items, j, this.holder.index);
								this.holder.index = j;
							}
						}else if(i > this.holder.index){
							for(var j = this.holder.index + 1; j < i; j++){
								_x = items[j].x; _y = items[j].y;
								items[j].moveTo(this.holder.x, this.holder.y);
								this.holder.x = _x;this.holder.y = _y;
								this.replaceItem(items, j, this.holder.index);
								this.holder.index = j;
							}
						}
						
						break;
					//到了目标元素上
					}*/
				
				//判断左侧区域
				if(items[i].x < x && x < items[i].x + 87 && items[i].y < y && items[i].y + 76 > y){
					hit = 1;
					if(items[i] == this.curItem){
						return false;
					}
					//如果不是同一个元素
					if(ItemFactory.Move.curUpItem != items[i]){
						index = i;
						//ItemFactory.Move
						window.clearTimeout(this.upOnTimer);
						if(this.curUpItem){
							this.curUpItem.toNormal();
						}
						this.upOnTimer = window.setTimeout(function(){
							ItemFactory.Move.curUpItem = items[index];
							items[index].toFolderView();
						},200);
					}
				}else{ items[i].toNormal();
					if(items[i].x > x && x > items[i].x - 60 && items[i].y < y && items[i].y + 76 > y){
						if(i < this.holder.index){
							for(var j = this.holder.index - 1; j >= i; j--){
								_x = items[j].x; _y = items[j].y;
								items[j].moveTo(this.holder.x, this.holder.y);
								this.holder.x = _x;this.holder.y = _y;
								this.replaceItem(items, j, this.holder.index);
								this.holder.index = j;
							}
						}else if(i > this.holder.index){
							for(var j = this.holder.index + 1; j < i; j++){
								_x = items[j].x; _y = items[j].y;
								items[j].moveTo(this.holder.x, this.holder.y);
								this.holder.x = _x;this.holder.y = _y;
								this.replaceItem(items, j, this.holder.index);
								this.holder.index = j;
							}
						}
						break;
						}
					//到了目标元素上
				}
			}
			if(!hit){ //清除状态
				if(this.curUpItem){
					this.curUpItem.toNormal();
					this.curUpItem = null;
				}
			}
			return [_i,item];
		},
		replaceItem : function(items, i, j){
			var tmp = items[i];
			items[i] = items[j];
			items[j] = tmp;
		}
	},
	openList : {},
	folderItems : [],
	curFolder : null,
	openFolder : function(id){
		var item = this.getItemById(id),
			childs = this.origData[id], html = [], c;
		if(this.curFolder){
			//关闭
			
		}else{
			//打开
			var df = document.createDocumentFragment(), pos, ins, curItems = [];

			for(var i = 0, len = childs.length , meta; i < len; i++){
				pos = ItemFactory.countXY(i);
				ins = new Item(childs[i]);
				df.appendChild(ins.genDom(pos[0], pos[1]));
				curItems.push(ins);
			}
			c = $('_finder_folder');
			c.innerHTML = '';
			c.appendChild(df);
			this.folderItems = curItems;
			this.curFolder = item[1];
			QZFL.css.addClassName(item[1].dom, 'item_open');
			if(item[0] > 6){
				QZFL.effect.run(item[1].dom.parentNode, {
					'top' : Math.floor(item[0]/7) * -117
				},{
					'easing' : 'ease-in',
					'duration' : 400
				});
			}
			QZFL.css.addClassName($('_finder_container'), 'popup_qzonefinder_in');
			window.setTimeout(function(){
				//绑定下关闭事件
				QZFL.event.addEvent(c, 'click', ItemFactory.folderClick);
				QZFL.event.addEvent($('_finder_container'), 'click', ItemFactory.closeFolder);
			},20);
			$('_finder_folder_arrow').style.left = item[1].x + 54 + 'px';
		}
	},
	folderClick : function(evt){
		QZFL.event.cancelBubble(evt);
	},
	closeFolder : function(evt){
		var dom = ItemFactory.curFolder.dom, me = this, fListCon = $('_finder_folder_list');
		
		QZFL.event.removeEvent($('_finder_container'), 'click', ItemFactory.closeFolder);
		ItemFactory.curFolder = null;
		QZFL.effect.run(dom.parentNode, {
				'top' : 0
			},{
				'easing' : 'ease-in',
				'duration' : 200
			});
		QZFL.css.addClassName(fListCon, 'popup_qzonefinder_folder_close');
		window.setTimeout(function(){
			var RV = QZFL.css.removeClassName;
			RV(me, 'popup_qzonefinder_in');
			RV(dom, 'item_open');
			
			RV(fListCon, 'popup_qzonefinder_folder_close');
		},180);
	},
	getItemFromNextPage:function(){
		
	}
};
//ItemFactory.init(QZONE.Finder.db.getFullList());
